import 'package:boss/main.dart';
import 'package:boss/models/role.dart';
import 'package:boss/ui/widget/alert/alert.dart';
import 'package:boss/ui/widget/loading/loading.dart';
import 'package:hi_common/hi_common.dart';
import 'package:flutter/material.dart';
import 'package:async/async.dart';

class RoleProvider extends ChangeNotifier {
  List<Role> roles;

  Future<Result<List<Role>>> initData() async {
    try {
      var res = await api.queryRoles();
      if (!res.successful()) {
        return Result.error(res.msg);
      }

      roles = res.data;

      return Result.value(res.data);
    } catch (e) {
      return Result.error(e.toString());
    }
  }

  Future<void> saveRole(Role role) async {
    if (!RegUtil.testNotEqEmpty(role.roleName)) {
      toast('请输入角色名称');
      return;
    }

    try {
      showLoadingToast();
      var isUpdated = role.roleId != null;

      var res = await api.addOrUpdateRule(role);
      if (!res.successful()) {
        toast(res.msg);
        return;
      }

      if (isUpdated) {
        var index = roles.indexWhere((item) => item.roleId == role.roleId);
        roles[index] = res.data;
      } else {
        roles.add(res.data);
      }
      notifyListeners();

      Navigator.pop(GlobalPageContext.instance.context);
    } catch (e) {
      toast(e.toString());
      return;
    } finally {
      hideLoadingToast();
    }
  }

  deleteRole(Role role) async {
    showAlert(
      GlobalPageContext.instance.context,
      content: '确认删除该角色么？',
      onCancel: (context) {
        Navigator.pop(context);
      },
      onConfirm: (context) async {
        Navigator.pop(context);

        try {
          showLoadingToast();

          var res = await api.deleteRole(role.roleId);
          if (!res.successful()) {
            toast(res.msg);
            return;
          }

          roles.removeWhere((item) => item.roleId == role.roleId);
          notifyListeners();

          Navigator.pop(GlobalPageContext.instance.context);
        } catch (e) {
          toast(e.toString());
        } finally {
          hideLoadingToast();
        }
      },
    );
  }
}
